package com.example.demo4.xml;

import com.example.demo4.BeanDefinition;
import com.example.demo4.MutablePropertyValues;
import com.example.demo4.PropertyValue;
import com.example.demo4.support.BeanDefinitionReader;
import com.example.demo4.support.BeanDefinitionRegistry;
import com.example.demo4.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * xml 解释器 实现类
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    //声明注册表对象
    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        registry = new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        ParsingXML(configLocation);
    }

    private void ParsingXML(String configLocation) throws DocumentException {
        SAXReader reader = new SAXReader();
        //使用xml获取具体的配置文件
        InputStream asStream = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        //将当前流 给dom4j进行读取
        Document document = reader.read(asStream);

        //获取root下所有的节点
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        elements.stream().forEach(element -> {
            String beanId = element.attributeValue("id");
            String className = element.attributeValue("class");
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setClassName(className);
            beanDefinition.setId(beanId);
            //bean标签下面所有的 property属性
            List<PropertyValue> propertyValues = new ArrayList<>();
            //获取bean下面的 property属性
            List<Element> propertyLists = element.elements("property");
            propertyLists.stream().forEach(element1 -> {
                String name = element1.attributeValue("name");
                String ref = element1.attributeValue("ref");
                String value = element1.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, ref, value);
                propertyValues.add(propertyValue);
            });
            beanDefinition.setPropertyValues(new MutablePropertyValues(propertyValues));
            System.out.println("beanDefinition = " + beanDefinition);
            registry.registerBeanDefinition(beanId, beanDefinition);
        });

    }

}
